package com.tony.mulitithread.utils;

import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 多线程查全表通用工具类
 */
public class ThreadPoolUtils2 {

    /**
     * 多线程查全表(通用)
     * 注解@Async线程方法
     *
     * @param totalNum
     * @param threadAsyncTableDataQuery
     * @return
     * @throws Exception
     */
    public static List<T> threadAsync(int totalNum, ThreadAsyncTableDataQuery threadAsyncTableDataQuery) throws Exception {

        List<Future<List<T>>> list = new ArrayList<>();
        if (totalNum > 10) {
            int remainder = totalNum % 10;
            int size = remainder > 0 ? totalNum / 10 + 1 : totalNum / 10;
            for (int i = 0; i < 10; i++) {
                int page = i * size;
                Future<List<T>> pv = threadAsyncTableDataQuery.selectTableDataAsync(page, size);
                list.add(pv);
            }
        } else {
            Future<List<T>> ts = threadAsyncTableDataQuery.selectTableDataAsync(0, 10);
            list.add(ts);
        }
        return ThreadPoolUtils2.taskValue(list);
    }

    /**
     * 拿取线程里的数据
     *
     * @param taskFutures
     * @return
     */
    public static List<T> taskValue(List<Future<List<T>>> taskFutures) {
        List<T> result = new ArrayList<>();
        try {
            for (Future<List<T>> future : taskFutures) {
                List<T> obj = future.get();
                if (null != obj) {
                    result.addAll(obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
